<script setup lang="ts">
import { ref, onMounted, watch, toRef, toRefs } from "vue";
import * as echarts from "echarts"; //引入echarts核心模块
import axios from "axios"; //引入echarts核心模块
import { Search } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
// import Index from "./views/index/index.vue";

const value2 = ref([]);

const shortcuts = [
  {
    text: "近1小时",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setHours(start.getHours() - 1);
      return [start, end];
    },
  },
  {
    text: "近3小时",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setHours(start.getHours() - 3);
      return [start, end];
    },
  },
  {
    text: "近一天",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(start.getDate() - 1);
      return [start, end];
    },
  },
];
const chart = ref(); //创建dom引用

const xAxis_data = ref();
const series_data = ref();
const series_data1 = ref();

const initChart = async () => {
  if (chart.value == null) {
    return;
  }

  echarts.dispose(chart.value);
  var myChart = echarts.init(chart.value);
  myChart.setOption({});
  let option = {
    tooltip: {
      trigger: "axis",
      formatter: function (params) {
        const eun = xAxis_data.value[params[0].dataIndex];
        const current_cycle_time = series_data.value[params[0].dataIndex];
        const timeDisplay = series_data1.value[params[0].dataIndex];
        const targetCycle = asCycleData.value !== null ? `目标节拍: ${asCycleData.value}` : "";
        return `<div>EUN:${eun}</div><div>时间: ${timeDisplay}</div><div>节拍: ${current_cycle_time}</div><div>${targetCycle}</div>`;
      },
    },
    toolbox: {
      show: true,
      feature: {
        mark: { show: true },
        dataView: { show: true, readOnly: false },
        magicType: { show: true, type: ["line", "bar"] },
        restore: { show: true },
        saveAsImage: { show: true },
      },
    },

    title: {
      text: "单工位节拍分析",
      left: "center",
      textStyle: {
        color: "black", // 设置标题颜色为白色
      },
      subtext: "单位：s",
      subtextStyle: {
        fontWeight: "bold",
      },
    },
    xAxis: {
      type: "category",
      data: series_data1.value,
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "节拍",
        data: series_data.value,
        type: "bar",
        markLine: {
          data: [
            {
              type: "average",
              name: "平均值",
              show: true,
              lineStyle: { type: "solid", color: "green" },
              label: {
                show: true,
                //formatter: function (params) {
                //  return "当前平均：" + average.value;
                //},
              },
            },
          ],
        },
        itemStyle: {
          normal: {
            color: function (params) {
              // 如果数据点的值超过markLine的值，则返回橙色
              if (params.value > asCycleData.value) {
                return "orange";
              }
              // 否则，返回默认颜色
              return "lightblue"; // 或者你可以保留原来的颜色设置
            },
          },
        },
        label: {
          show: true,
          position: "top",
          formatter: function (data) {
            // 获取markLine的值，假设asCycleData.value是你的markLine的y轴值
            const markLineValue = asCycleData.value;

            // 只有当数据点的值超过markLine的值时，才返回数值
            return data.value > markLineValue ? data.value : "";
          },

          color: "black", // 文字颜色
          fontSize: 12, // 文字大小
        },
      },
    ],
    dataZoom: [
      {
        type: "slider",
        start: 0,
        end: 100,
      },
      {
        type: "inside",
        start: 90,
        end: 100,
      },
    ],
  };
  let targetMarkLines: any[] = [];

  const targetCycle = asCycleData.value;
  const deviation = targetCycle * 0.03;
  let markLineSeriesExists = option.series.some((serie) => serie.id === "markLineSeries");
  if (!markLineSeriesExists) {
    option.series.push({
      id: "markLineSeries",
      type: "line",
      markLine: {
        symbol: ["none", "none"], // 确保两端箭头都不显示
        silent: true, // 不响应鼠标事件
        data: [
          // 目标节拍线
          { yAxis: targetCycle, label: { show: true, formatter: `目标节拍：${targetCycle}` } },
          // 目标节拍+3%线
          { yAxis: targetCycle + deviation, label: { show: false }, lineStyle: { color: "orange" } },
          // 目标节拍-3%线
          { yAxis: targetCycle - deviation, label: { show: false }, lineStyle: { color: "orange" } },
        ],
      },
      showSymbol: false, // 系列数据点不显示
      itemStyle: {
        opacity: 0, // 数据点透明，实际上这里因为data为空，所以不会显示任何点
      },
      data: [], // 确保该系列本身没有数据点显示
    });
  } else {
    // 如果markLineSeries已存在，则找到它并更新其markLine配置
    const markLineSeries = option.series.find((serie) => serie.id === "markLineSeries");
    if (markLineSeries) {
      // 更新或添加markLine数据
      if (!markLineSeries.markLine.data.some((line) => line.yAxis === targetCycle)) {
        markLineSeries.markLine.data.push({ yAxis: targetCycle, label: { show: true, formatter: `目标节拍：${targetCycle}` } }, { yAxis: targetCycle + deviation, label: { show: true, formatter: `目标节拍+3%：${targetCycle + deviation}` } }, { yAxis: targetCycle - deviation, label: { show: true, formatter: `目标节拍-3%：${targetCycle - deviation}` } });
      }
    }
  }

  myChart.setOption(option);
};

onMounted(() => {
  fetchAsCycleData();
  const now = new Date();
  const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  value2.value = [todayStart, now];

  const stationFromUrl = router.currentRoute.value.query.station;
  if (stationFromUrl) {
    value3.value = stationFromUrl;
  }

  const start_time = formatDate(value2.value[0]);
  const end_time = formatDate(value2.value[1]);
  construct_url = `http://10.64.35.32:8000/as_manage_analysis/get_OutputLoopa_data/?start_time=${start_time}&end_time=${end_time}&station=${value3.value}&page_size=1001`;

  if (value2.value.length === 2 && value3.value) {
    console.log("自动触发查询");
    use_show_data_in_html(); // 直接调用查询方法
  }
});

const value3 = ref("");
const router = useRouter();
const options = [
  { value: "2490M", label: "2490M" },
  { value: "1010M", label: "1010M" },
  { value: "1410M", label: "1410M" },
  { value: "2010M", label: "2010M" },
  { value: "1020A", label: "1020A" },
  { value: "1030A", label: "1030A" },
  { value: "1050M", label: "1050M" },
  { value: "1060M", label: "1060M" },
  { value: "1070M", label: "1070M" },
  { value: "1080A", label: "1080A" },
  { value: "1090M", label: "1090M" },
  { value: "1100M", label: "1100M" },
  { value: "1110A", label: "1110A" },
  { value: "1120A", label: "1120A" },
  { value: "1160A", label: "1160A" },
  { value: "1170M", label: "1170M" },
  { value: "1180M", label: "1180M" },
  { value: "1190A", label: "1190A" },
];

const maxCycle = ref({ value: null, eun: "", time: "" });
const minCycle = ref({ value: null, eun: "", time: "" });

const calculateStats = () => {
  let maxValue = null;
  let minValue = null;
  for (let i = 0; i < series_data.value.length; i++) {
    const current = series_data.value[i];
    const eun = xAxis_data.value[i];
    const time = series_data1.value[i];
    if (maxValue === null || current > maxValue) {
      maxValue = current;
      maxCycle.value = { value: current, eun, time };
    }
    if (minValue === null || current < minValue) {
      minValue = current;
      minCycle.value = { value: current, eun, time };
    }
  }
  console.log("最大节拍:", maxCycle.value);
  console.log("最小节拍:", minCycle.value);
};

watch(
  [series_data, xAxis_data, series_data1],
  () => {
    calculateStats();
  },
  { deep: true }
);

function formatDate(d: string) {
  var date = new Date(d);
  var YY = date.getFullYear() + "-";
  var MM = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
  var DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  var hh = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
  var mm = (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) + ":";
  var ss = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  return YY + MM + DD + " " + hh + mm + ss;
}

// 根据时间范围获取对应的数据
const show_data_in_html = (url: string) => {
  // 发起后端请求
  axios.get(url).then((res) => {
    console.log(res);
    console.log("0:", res.data);
    console.log("目标:", asCycleData.value);

    xAxis_data.value = res.data.map((item: any) => item.eun);
    series_data.value = res.data.map((item: any) => item.last_cycle_time / 10);
    series_data1.value = res.data.map((item: any) => item.time);

    console.log(xAxis_data.value);
    console.log(series_data.value);
    console.log(series_data1.value);

    initChart();
  });
};

var construct_url = "";
watch([value2, value3], () => {
  const start_time: Object = formatDate(value2.value[0]);
  const end_time: Object = formatDate(value2.value[1]);
  construct_url = "http://10.64.35.32:8000/as_manage_analysis/get_OutputLoopa_data/" + "?start_time=" + start_time?.toString() + "&end_time=" + end_time?.toString() + "&station=" + value3.value + "&page_size=" + 1001;
});

const asCycleData = ref(null);

const fetchAsCycleData = async (station) => {
  try {
    const response = await axios.get("http://10.64.35.32:8000/as_manage_analysis/get_as_cycle_data/?page=1&page_size=1");
    if (response.data && response.data && response.data[0].cycle[station]) {
      asCycleData.value = response.data[0].cycle[station];
      console.log("目标:", asCycleData.value);
      initChart(); // 数据更新后重新初始化图表
    } else {
      console.error(`未找到${station}的值`);
    }
  } catch (error) {
    console.error("获取数据失败", error);
  }
};

const use_show_data_in_html = async () => {
  console.log(construct_url);
  await show_data_in_html(construct_url);

  // 确保在获取新的图表数据后，再更新 asCycleData 的值
  await fetchAsCycleData(value3.value);

  // 更新 asCycleData 后，重新初始化图表以应用新的 markLine 值
  initChart();
};
</script>
<template>
  <h3 style="display: flex">单工位节拍分析:</h3>
  <el-row>
    <div class="block">
      <el-date-picker v-model="value2" type="datetimerange" :shortcuts="shortcuts" range-separator="To" start-placeholder="起始日期" end-placeholder="结束日期" />
    </div>
    <div class="block">
      <el-select v-model="value3" placeholder="选择工位" style="width: 240px">
        <el-input slot="prepend" v-model="value3" placeholder="手动输入工位编号，如2490M" />
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </div>
    <div class="block">
      <el-button type="primary" :icon="Search" @click="use_show_data_in_html">查询</el-button>
    </div>
  </el-row>
  <div>
    <div ref="chart" style="height: 500px; width: 1300px"></div>
    <el-table :data="[maxCycle, minCycle]" style="width: 100%; margin-top: 1px">
      <el-table-column prop="eun" label="EUN" width="180"> </el-table-column>
      <el-table-column prop="time" label="时间" width="180"> </el-table-column>
      <el-table-column prop="value" label="节拍(s)">
        <template #default="{ row }">
          <span v-if="row === maxCycle">最大：{{ row.value }}</span>
          <span v-else-if="row === minCycle">最小：{{ row.value }}</span>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<style scoped>
h3 {
  color: black;
}

.block {
  padding: 20px;
  text-align: center;
  /* border-right: solid 1px var(--el-border-color); */
  flex: 1;
}
.block:last-child {
  border-right: none;
}
.block .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
.el-select .el-scrollbar__wrap {
  max-height: 50px !important; /* 设定一个合适的高度 */
  overflow-y: auto !important; /* 启用垂直滚动 */
}
</style>
